﻿using System;
using System.Collections.Generic;
using Microsoft.Office.PowerPoint.STAMP.Core;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Office.Interop.PowerPoint;

namespace Microsoft.Office.PowerPoint.STAMP
{
    public partial class ThisAddIn
    {
        private Application _application;

        private static readonly List<string> TempFileNameList = new List<string>();

        internal static void AddTempFileNameToList(string tempItem)
        {
            TempFileNameList.Add(tempItem);
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            _application = Globals.ThisAddIn.Application;
            _application.WindowSelectionChange += WindowSelectionChange;
        }

        /// <summary>
        /// Event handler for the selection change event raised by the PowerPoint application.
        /// </summary>
        /// <param name="sel">The current selection in the application.</param>
        void WindowSelectionChange(Selection sel)
        {
            SelectionChangeProcessor.HandleSelectionChange(sel);
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            _application.WindowSelectionChange -= WindowSelectionChange;

            foreach (var tempFileName in TempFileNameList)
            {
                if (System.IO.File.Exists(tempFileName))
                {
                    try
                    {
                        System.IO.File.Delete(tempFileName);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        // suppress display of message if the removal of temp file fails
                    }
                    catch (Exception ex)
                    {
                        bool rethrow = ExceptionPolicy.HandleException(ex, "Global Policy");
                        if (rethrow)
                            throw;
                    }
                }
            }
        }

        /// <summary>
        /// Overrides the CreateRibbonExtensibilityObject.
        /// 
        /// </summary>
        /// <returns></returns>
        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            return new StampRibbon();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += ThisAddIn_Startup;
            this.Shutdown += ThisAddIn_Shutdown;
        }

        #endregion
    }
}
